package com.itoffer.web;

import com.itoffer.pojo.Applicant;
import com.itoffer.service.ApplicantService;
import com.itoffer.service.impl.ApplicantServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private ApplicantService applicantService = new ApplicantServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取来自注册页面的参数
        String applicant_email = req.getParameter("applicant_email");
        String applicant_pwd = req.getParameter("applicant_pwd");
        String register_time = req.getParameter("register_time");

//        System.out.println(applicant_email);
//        System.out.println(applicant_pwd);
//        System.out.println(register_time);

        //封装applicant对象
        Applicant applicant = new Applicant();
        applicant.setApplicant_email(applicant_email);
        applicant.setApplicant_pwd(applicant_pwd);
        applicant.setApplicant_registerDate(register_time);

        //获取用户输入的验证码
        String checkCode = req.getParameter("checkCode");
        System.out.println("用户输入验证码为"+checkCode);

        //获取Session中存入的验证码
        HttpSession session = req.getSession();
        String checkCodeGen = (String)session.getAttribute("checkCodeGen");

        //比对验证码
        if(checkCode!=null||checkCode==""){
            if(!checkCodeGen.equalsIgnoreCase(checkCode)){
                //验证码错误
                resp.setContentType("text/json;charset=utf-8");
                resp.getWriter().write("yanError");
                return;
            }
        }




        //调用业务层注册方法注册
        boolean flag = applicantService.register(applicant);

        //判断注册成功与否
        if(flag){
            //注册成功，跳转到注册成功页面
           resp.setContentType("text/json;charset=utf-8");
           resp.getWriter().write("success");
        }else{
            //注册失败
            resp.setContentType("text/json;charset=utf-8");
            resp.getWriter().write("fail");

        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
